import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { Button, Table, Select, Input, message } from 'antd';
import Modal from '../../../../../../components/Modal';
import CodeMap from './codeMap';
import MapResult from './mapResult';
import { TYPE_OPTIONS } from '../../../../../../utils/constant';
import { cloneDeep } from 'lodash';

// 取出对象中指定属性 返回新的对象
const extend = (obj, ...theArgs) => {
  const temp = {};
  theArgs.forEach((item) => {
    temp[item] = obj[item];
  });
  return temp;
};

// 对数组按某个属性进行归类
const getSortByKey = (data, key) => {
  const tempObj = {};
  data.forEach((item) => {
    if (!tempObj[item[key]]) {
      tempObj[item[key]] = [item];
    } else {
      tempObj[item[key]].push(item);
    }
  });
  return tempObj;
};

const SetUp = forwardRef((props, ref) => {
  const { value } = props;

  const [data, setData] = useState([]);
  const codeMapRef = useRef();

  useImperativeHandle(ref, () => ({
    getData: () => {
      data.forEach((item) => {
        for (const key in item) {
          if (item[key] === '') {
            throw '请完善映射设置';
          }
        }
      });
      // 将前端数据转为后端需要的结构
      // code映射集合
      const codeMaps = [];
      const tempList = data.filter((item) => !!item.codeMap);
      tempList.forEach((item) => {
        item.codeMap.forEach((val) => {
          for (let key in val) {
            const extraObj = extend(val, 'destKey', 'destCode', 'destDesc');
            if (key.includes('srcCode')) {
              const thirdInterfaceId = key.split('-')[1];
              const srcKey = item[`thirdPath-${thirdInterfaceId}`];
              codeMaps.push({
                srcKey,
                thirdInterfaceId,
                srcCode: val[key],
                ...extraObj,
              });
            }
          }
        });
      });
      // 返回值映射集合
      const returningMaps = [];
      data.forEach((item) => {
        for (let key in item) {
          const extraObj = extend(item, 'innerPath', 'isReturning', 'type');
          if (key.includes('thirdPath')) {
            const thirdInterfaceId = key.split('-')[1];
            returningMaps.push({
              thirdPath: item[key],
              thirdInterfaceId,
              ...extraObj,
            });
          }
        }
      });
      return { returningMaps, codeMaps };
    },
  }));

  useEffect(() => {
    // 将后端数据转为前使用的数据
    value.returningMaps && getTransferUseData(value.returningMaps);
  }, [value.returningMaps]);

  const getTransferUseData = (sourceData) => {
    // 返回值映射 码值映射
    const tempReturningMaps = [];
    const returnObj = getSortByKey(sourceData, 'innerPath');
    for (let key in returnObj) {
      const { isReturning, type } = returnObj[key][0];
      const temp = {
        innerPath: key,
        isReturning,
        type,
      };
      returnObj[key].forEach(({ thirdInterfaceId, thirdPath }) => {
        temp[`thirdPath-${thirdInterfaceId}`] = thirdPath;
      });
      tempReturningMaps.push(temp);
    }
    const tempCodeMap = [];
    const codeObj = getSortByKey(value.codeMaps, 'destCode');
    for (let key in codeObj) {
      const { destDesc, destKey } = codeObj[key][0];
      const temp = {
        destCode: key,
        destDesc,
        destKey,
      };
      codeObj[key].forEach(({ thirdInterfaceId, srcCode }) => {
        temp[`srcCode-${thirdInterfaceId}`] = srcCode;
      });
      tempCodeMap.push(temp);
    }
    tempReturningMaps.forEach((item) => {
      const codes = tempCodeMap.filter((val) => val.destKey === item.innerPath);
      if (codes.length) {
        item.codeMap = codes;
      }
    });
    setData(tempReturningMaps);
  };

  const handleAdd = () => {
    const { thirdList } = value;
    const tempData = cloneDeep(data);
    const tempObj = {
      innerPath: '',
      type: 0,
      isReturning: 1,
    };
    thirdList.forEach((item) => {
      tempObj[`thirdPath-${item.id}`] = '';
    });
    tempData.push(tempObj);
    setData(tempData);
  };

  const handleReview = () => {
    const newMap = data.map((item) => item.innerPath);
    const resultObj = getFormatObject(newMap);
    Modal.open({
      title: '映射预览',
      width: '600px',
      content: <MapResult resultObj={resultObj} />,
      maskClosable: false,
      isOkBtn: false,
      isCancelBtn: true,
      cancel: () => {
        Modal.close();
      },
    });
  };

  const getFormatObject = (data) => {
    const result = {};
    data.forEach((item) => {
      const itemList = item.split('.');
      itemList.reduce((prev, next, index) => {
        if (!prev[next]) prev[next] = {};
        if (index === itemList.length - 1) prev[next] = '';
        return prev[next];
      }, result);
    });
    return result;
  };

  const handleChange = (value, index, key) => {
    const tempData = [...data];
    tempData[index][key] = value;
    setData(tempData);
  };

  const handleMap = (record, index) => {
    if (!record.innerPath) return message.warning('请填写key值!');
    Modal.open({
      title: '码值映射设置',
      width: '1000px',
      content: <CodeMap {...props} record={record} ref={codeMapRef} />,
      maskClosable: false,
      ok: () => {
        try {
          const tempData = cloneDeep(data);
          tempData[index]['codeMap'] = codeMapRef.current.getData();
          setData(tempData);
          Modal.close();
        } catch (error) {
          message.warning(error);
        }
      },
    });
  };

  const handleDelete = (index) => {
    const temp = [...data];
    temp.splice(index, 1);
    setData(temp);
  };
  const columns = [
    {
      title: '源key',
      children: value.thirdList.map((item) => ({
        title: item.name,
        dataIndex: `thirdPath-${item.id}`,
        render: (text, _, index) => (
          <Input value={text} onChange={(e) => handleChange(e.target.value, index, `thirdPath-${item.id}`)} />
        ),
      })),
    },
    {
      title: '映射key',
      dataIndex: 'innerPath',
      render: (text, _, index) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, index, 'innerPath')} />
      ),
    },
    {
      title: '数据类型',
      dataIndex: 'type',
      render: (text, _, index) => (
        <Select placeholder='请选择' value={text} onChange={(value) => handleChange(value, index, 'type')}>
          {TYPE_OPTIONS.map((item, index) => (
            <Select.Option value={index} key={index}>
              {item}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '返回key(是否)',
      dataIndex: 'isReturning',
      render: (text, _, index) => (
        <Select value={text} onChange={(value) => handleChange(value, index, 'isReturning')}>
          {['否', '是'].map((item, index) => (
            <Select.Option key={index} value={index}>
              {item}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, index) => (
        <>
          <Button type='text' onClick={() => handleMap(record, index)} style={{ marginRight: '20px' }}>
            码值映射
          </Button>
          <Button type='text' onClick={() => handleDelete(index)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <div className='set'>
      <Table dataSource={data} bordered columns={columns} rowKey={(_, index) => index} pagination={false} />
      <div style={{ marginTop: '20px' }}>
        <Button onClick={handleAdd} style={{ marginRight: '20px' }}>
          增加
        </Button>
        {!!data.length && <Button onClick={() => handleReview()}>映射预览</Button>}
      </div>
    </div>
  );
});
export default SetUp;
